In [1]:
%pylab inline
from datetime import date, timedelta, datetime
In [2]:
with load('data/numpy/SPY.npz') as loadData:
optionroot = loadData['optionroot']
quotedate = loadData['quotedate']
expiration = loadData['expiration']
underlying = loadData['underlying']
call_put = loadData['call_put']
strike = loadData['strike']
last = loadData['last']
bid = loadData['bid']
ask = loadData['ask']
volume = loadData['volume']
impliedvol = loadData['impliedvol']
delta = loadData['delta']
gamma = loadData['gamma']
theta = loadData['theta']
vega = loadData['vega']
In [3]:
ref = find(~(quotedate[0:-1] == quotedate[1:]))
ref = ref + 1
ref = append(0,ref)
ref
Out[3]:
In [4]:
tradingDays = quotedate[ref]
tradingDays
Out[4]:
In [5]:
ticker = underlying[ref]
ticker
Out[5]:
In [6]:
plot(tradingDays,ticker)
Out[6]:
In [7]:
contractLength = expiration - quotedate
def pullDays(x):
return x.days
pullDays = vectorize(pullDays)
contractDaysLeft = pullDays(contractLength)
contractDaysLeft
Out[7]:
In [100]:
In [127]:
exposure = 10
bank = zeros(len(tradingDays) + 1)
bank[0] = 10000
# holdings = dict()
holdings['optionroot'] = array([])
holdings['numContracts'] = array([])
for i in range(len(tradingDays)):
currentDay = tradingDays[i]
if shape(holdings['optionroot'])[0] == 0: # If you haven't taken out a position, take one out
ref = (quotedate == currentDay) & (call_put == 'put') & (contractDaysLeft < 40)
lengthChoice = contractDaysLeft[ref].max()
ref = ref & (contractDaysLeft == lengthChoice)
deltaChoice = abs(delta)[ref][(abs(delta[ref])>0.3)].min()
ref = ref & (abs(delta) == deltaChoice)
# Purchase
numContracts = bank[i] * exposure // (strike[ref] * 100)
bank[i] += numContracts * last[ref]*100
holdings['optionroot'] = append(holdings['optionroot'],optionroot[ref][0])
holdings['numContracts'] = append(holdings['numContracts'],numContracts)
# holdings['purchasePrice']
# print(("Purchased:\n Root: %s\n Strike: %0.2f \n"+
# " Last: %0.2f \n Bid: %0.2f \n"+
# " Ask: %0.2f \n Volume: %d\n\n"+
# "Current Bank: %0.2f")
# %(optionroot[ref][0],strike[ref],last[ref],bid[ref],ask[ref],volume[ref],bank[i]))
else:
ref = (quotedate == currentDay) & (call_put == 'put') & (optionroot == holdings['optionroot'][0])
if last[ref] < 0.3:
# print(" Root: %s\nStrike: %0.2f \n Last: %0.2f \n Bid: %0.2f \n Ask: %0.2f \nVolume: %d"
# %(optionroot[ref][0],strike[ref],last[ref],bid[ref],ask[ref],volume[ref]))
bank[i] -= holdings['numContracts'][0] * last[ref]*100
holdings['optionroot'] = array([])
holdings['numContracts'] = array([])
elif contractDaysLeft[ref] < 2:
# print(" Root: %s\nStrike: %0.2f \n Last: %0.2f \n Bid: %0.2f \n Ask: %0.2f \nVolume: %d"
# %(optionroot[ref][0],strike[ref],last[ref],bid[ref],ask[ref],volume[ref]))
bank[i] -= holdings['numContracts'][0] * last[ref]*100
holdings['optionroot'] = array([])
holdings['numContracts'] = array([])
if bank[i] < 10:
break
bank[i+1] = bank[i]
In [132]:
shape(holdings['optionroot'])[0]
Out[132]:
In [133]:
holdings['numContracts']
Out[133]:
In [134]:
i
Out[134]:
In [142]:
figure(figsize=(16,8))
plot(tradingDays,bank[1:])
plot(tradingDays,ticker)
grid(True)
In [157]:
fig, ax1 = plt.subplots(figsize=(16,8))
t = np.arange(0.01, 10.0, 0.01)
s1 = np.exp(t)
ax1.plot(tradingDays,bank[1:],'b')
ax1.set_xlabel('Time (Years)')
# Make the y-axis label and tick labels match the line color.
ax1.set_ylabel('Bank Account ($)', color='b')
for tl in ax1.get_yticklabels():
tl.set_color('b')
grid(True)
ax2 = ax1.twinx()
s2 = np.sin(2*np.pi*t)
ax2.plot(tradingDays,ticker,'r')
ax2.set_ylabel('The Underlying ($)', color='r')
for tl in ax2.get_yticklabels():
tl.set_color('r')
title('Initial basic strategy -- Writing puts')
grid(True)
In [ ]: